import {Component, ViewChild} from '@angular/core';
import {App, Nav, Platform, ToastController} from 'ionic-angular';
import {StatusBar} from '@ionic-native/status-bar';
import {SplashScreen} from '@ionic-native/splash-screen';
import {LoginPage} from "../pages/login/login";

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage: any = sessionStorage.session ? "TabsPage" : "LoginPage";

  private backButtonPressed: boolean = false;

  @ViewChild('myNav') nav: Nav;

  constructor(public platform: Platform,
              statusBar: StatusBar,
              splashScreen: SplashScreen,
              public toastCtrl: ToastController,
              private app: App) {
    this.platform.ready().then(() => {
      statusBar.backgroundColorByHexString("#fde5da");
      statusBar.styleDefault();
      splashScreen.hide();

      this.exitApp();
    });
  }


  private exitApp() {
    this.platform.registerBackButtonAction(() => {
      //控制modal、系统自带提示框
      let overlay = this.app._appRoot._overlayPortal.getActive() || this.app._appRoot._modalPortal.getActive();
      if (overlay) {
        overlay.dismiss();
        return;
      }
      let activeVC = this.nav.getActive();
      let page = activeVC.instance;
      if (page instanceof LoginPage) {//查看当前页面是否是登陆页面
        this.showExit();
        return;
      }
      this.app.getActiveNav().pop();//剩余的情况全部使用全局路由进行操作
    }, 10);
  }


  private showExit() {
    if (this.backButtonPressed) {
      this.platform.exitApp();
    } else {
      this.presentToast();//再按一次退出
      this.backButtonPressed = true;
      setTimeout(() => {
        this.backButtonPressed = false;
      }, 2000)
    }
  }

  presentToast() {
    let toast = this.toastCtrl.create({
      message: '再按一次退出应用',
      duration: 2000,
      position: 'bottom'
    });
    toast.onDidDismiss(() => {
      console.log('Dismissed toast');
    });
    toast.present();
  }
}
